package top.xia17.plugins.fast.dynamic.datasource.mgmt;

import top.xia17.plugins.fast.common.model.Back;
import top.xia17.plugins.fast.common.model.PageData;
import top.xia17.plugins.fast.common.model.PageParam;
import top.xia17.plugins.fast.common.database.DbUtil;
import top.xia17.plugins.fast.common.database.jpa.JpaUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import top.xia17.plugins.fast.dynamic.datasource.dao.DatasourceEntity;

import java.util.List;
import java.util.Optional;

/**
 * 数据源管理api接口
 *
 * @author xia17
 * @date 2022/4/13
 */
@RequiredArgsConstructor
@RequestMapping("datasource/mgmt")
@ResponseBody
public class DatasourceMgmtRest {

    private final DatasourceService datasourceService;


    /**
     * 新增数据源
     *
     * @param resource /
     * @return /
     */
    @PostMapping("create")
    public Back<DatasourceEntity> create(@RequestBody DatasourceEntity resource) {
        DatasourceEntity entity = datasourceService.create(resource);
        return Back.ok(entity);
    }

    /**
     * 新增数据源
     *
     * @param resource /
     * @return /
     */
    @PostMapping("update")
    public Back<DatasourceEntity> update(@RequestBody DatasourceEntity resource) {
        DatasourceEntity entity = datasourceService.update(resource);
        return Back.ok(entity);
    }

    /**
     * 查询分页
     *
     * @param query     查询条件
     * @param pageParam 分页参数
     * @return /
     */
    @GetMapping("page")
    public Back<PageData<DatasourceEntity>> page(DatasourceQuery query, PageParam pageParam) {
        Page<DatasourceEntity> page = datasourceService.findAll(query, pageParam.toPageable());
        return Back.ok(JpaUtil.page(page));
    }

    /**
     * 查询列表
     *
     * @param query 查询条件
     * @return /
     */
    @GetMapping("list")
    public Back<List<DatasourceEntity>> list(DatasourceQuery query) {
        List<DatasourceEntity> list = datasourceService.findAll(query);
        return Back.ok(list);
    }

    /**
     * 切换启用状态
     *
     * @param id /
     * @return /
     */
    @PostMapping("switchEnabled/{id}")
    public Back<String> switchEnabled(@PathVariable("id") Long id) {
        datasourceService.switchEnabled(id);
        return Back.ok();
    }


    /**
     * 连接测试
     * 测试结果是成功时返回的code是 200
     * 测试结果是失败时返回的code是 201 ，data是错误信息
     *
     * @param url      连接地址
     * @param username 用户名
     * @param password 密码
     * @param driver   驱动
     * @return 测试结果
     */
    @PostMapping("test_connection")
    public Back<String> testConnection(String url, String username, String password, String driver) {
        // 连接测试
        Optional<String> optional = DbUtil.testConnection(url, username, password, driver);
        return optional
                .map(s -> new Back<>(201, "OK", "连接失败！" + s))
                .orElseGet(Back::ok);
    }


}
